package io.renren.modules.job.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.modules.behavior.entity.UserBehaviorLogEntity;
import io.renren.modules.behavior.service.UserBehaviorLogService;
import io.renren.modules.mahout.entity.CollaborativeFilteringEntity;
import io.renren.modules.mahout.service.CollaborativeFilteringService;
import io.renren.modules.task.entity.TaskRecordEntity;
import io.renren.modules.task.service.TaskRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

@Component
public class CollaborativeFilteringTask {

    public static final String MAHOUT_CODE = "mahoutCode";

    @Autowired
    private TaskRecordService taskRecordService;

    @Autowired
    private UserBehaviorLogService userBehaviorLogService;

    @Autowired
    private CollaborativeFilteringService collaborativeFilteringService;

    @Scheduled(fixedDelay = 5 * 1_000)
    public void mahout() {

        TaskRecordEntity taskRecord = taskRecordService.getOne(
                new QueryWrapper<TaskRecordEntity>().eq("task_code", MAHOUT_CODE)
        );

        Long taskData = taskRecord.getTaskData();

        List<UserBehaviorLogEntity> list = userBehaviorLogService.list(new QueryWrapper<UserBehaviorLogEntity>().gt("id", taskData));
        for (UserBehaviorLogEntity entity : list) {
            CollaborativeFilteringEntity cf = new CollaborativeFilteringEntity();
            cf.setUserId(entity.getUserId());
            cf.setItemId(entity.getItemId());
            switch (entity.getUserBehaviorType()) {
                case 1:
                    // 点赞
                    cf.setItemAccount(1.0);
                    break;
                case 2:
                case 4:
                    // 搜索
                    // 收藏
                    cf.setItemAccount(2.0);
                    break;
                case 3:
                    // 评论
                    cf.setItemAccount(0.5);
                    break;
                default:
                    cf.setItemAccount(0.0);
                    break;
            }

            collaborativeFilteringService.saveOrUpdateByUserAndItem(cf);

            // 将当前完成的记录到数据库的task_record表中
            taskRecord.setTaskData(cf.getId());
            taskRecordService.saveOrUpdate(taskRecord);
        }


    }


}
